<template>
  <div class="environments">
    <div class="page-header">
      <h2>环境管理</h2>
      <el-button type="primary" @click="showCreateDialog = true">
        <el-icon><Plus /></el-icon>
        创建环境
      </el-button>
    </div>

    <!-- 环境列表 -->
    <el-card>
      <el-table :data="environments" v-loading="loading" style="width: 100%">
        <el-table-column prop="name" label="环境名称" min-width="150" />
        <el-table-column prop="base_url" label="基础URL" min-width="200" />
        <el-table-column prop="description" label="描述" min-width="150" />
        <el-table-column prop="yaml_config" label="YAML配置" min-width="100">
          <template #default="scope">
            <el-tag v-if="scope.row.yaml_config" type="success" size="small">已配置</el-tag>
            <el-tag v-else type="info" size="small">未配置</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="is_active" label="状态" width="100">
          <template #default="scope">
            <el-tag :type="scope.row.is_active ? 'success' : 'info'">
              {{ scope.row.is_active ? '启用' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="created_at" label="创建时间" width="180">
          <template #default="scope">
            {{ formatDate(scope.row.created_at) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="250" fixed="right">
          <template #default="scope">
            <el-button size="small" @click="editEnvironment(scope.row)">编辑</el-button>
            <el-button size="small" type="primary" @click="viewYamlConfig(scope.row)">查看YAML</el-button>
            <el-button 
              size="small" 
              type="danger" 
              @click="deleteEnvironment(scope.row)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 创建/编辑对话框 -->
    <el-dialog
      v-model="showCreateDialog"
      :title="editingEnvironment ? '编辑环境' : '创建环境'"
      width="800px"
    >
      <el-form :model="environmentForm" :rules="formRules" ref="environmentFormRef" label-width="100px">
        <el-form-item label="环境名称" prop="name">
          <el-input v-model="environmentForm.name" placeholder="请输入环境名称" />
        </el-form-item>
        
        <el-form-item label="基础URL" prop="base_url">
          <el-input v-model="environmentForm.base_url" placeholder="请输入基础URL，如：http://api.example.com" />
        </el-form-item>
        
        <el-form-item label="环境描述" prop="description">
          <el-input
            v-model="environmentForm.description"
            type="textarea"
            :rows="3"
            placeholder="请输入环境描述"
          />
        </el-form-item>
        
        <el-form-item label="YAML配置" prop="yaml_config">
          <div class="yaml-editor-container">
            <div class="yaml-toolbar">
              <el-button size="small" @click="loadYamlTemplate">加载模板</el-button>
              <el-button size="small" @click="validateYaml">验证YAML</el-button>
              <el-button size="small" @click="formatYaml">格式化</el-button>
            </div>
            <el-input
              v-model="environmentForm.yaml_config"
              type="textarea"
              :rows="15"
              placeholder="请输入YAML配置内容"
              font-family="monospace"
              class="yaml-textarea"
            />
          </div>
        </el-form-item>
        
        <el-form-item label="状态">
          <el-switch v-model="environmentForm.is_active" />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showCreateDialog = false">取消</el-button>
          <el-button type="primary" @click="saveEnvironment" :loading="saving">
            保存
          </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- YAML配置查看对话框 -->
    <el-dialog
      v-model="showYamlDialog"
      title="YAML配置"
      width="800px"
    >
      <div v-if="selectedEnvironment">
        <div class="yaml-view-header">
          <h4>{{ selectedEnvironment.name }} - YAML配置</h4>
          <el-button size="small" @click="copyYamlConfig">复制配置</el-button>
        </div>
        <el-input
          v-model="selectedEnvironment.yaml_config"
          type="textarea"
          :rows="20"
          readonly
          font-family="monospace"
          class="yaml-textarea"
        />
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { environmentAPI } from '@/api'

export default {
  name: 'Environments',
  setup() {
    const loading = ref(false)
    const saving = ref(false)
    const showCreateDialog = ref(false)
    const showYamlDialog = ref(false)
    const editingEnvironment = ref(null)
    const selectedEnvironment = ref(null)
    const environments = ref([])
    const environmentFormRef = ref(null)

    const environmentForm = reactive({
      name: '',
      base_url: '',
      description: '',
      yaml_config: '',
      is_active: true
    })

    const formRules = {
      name: [{ required: true, message: '请输入环境名称', trigger: 'blur' }],
      base_url: [{ required: true, message: '请输入基础URL', trigger: 'blur' }]
    }

    const loadEnvironments = async () => {
      loading.value = true
      try {
        const response = await environmentAPI.getList()
        environments.value = response.results || []
      } catch (error) {
        console.error('加载环境列表失败:', error)
      } finally {
        loading.value = false
      }
    }

    const editEnvironment = (environment) => {
      editingEnvironment.value = environment
      Object.assign(environmentForm, {
        name: environment.name,
        base_url: environment.base_url,
        description: environment.description,
        yaml_config: environment.yaml_config || '',
        is_active: environment.is_active
      })
      showCreateDialog.value = true
    }

    const viewYamlConfig = (environment) => {
      selectedEnvironment.value = environment
      showYamlDialog.value = true
    }

    const loadYamlTemplate = () => {
      const template = `# 环境配置模板
environment:
  name: "${environmentForm.name || '环境名称'}"
  base_url: "${environmentForm.base_url || 'http://api.example.com'}"
  
# 全局配置
global:
  timeout: 30
  retry_times: 3
  headers:
    Content-Type: "application/json"
    User-Agent: "API-Test-Platform/1.0"

# 数据库配置
database:
  host: "localhost"
  port: 3306
  username: "root"
  password: "password"
  database: "test_db"

# 缓存配置
cache:
  redis_host: "localhost"
  redis_port: 6379
  redis_db: 0

# 日志配置
logging:
  level: "INFO"
  file: "logs/environment.log"
  max_size: "10MB"
  backup_count: 5

# 邮件配置
email:
  smtp_server: "smtp.example.com"
  smtp_port: 587
  username: "test@example.com"
  password: "password"
  use_tls: true

# 自定义变量
variables:
  api_version: "v1"
  timeout: 30
  max_retries: 3`
      
      environmentForm.yaml_config = template
      ElMessage.success('已加载YAML模板')
    }

    const validateYaml = async () => {
      try {
        if (!environmentForm.yaml_config.trim()) {
          ElMessage.warning('YAML配置为空')
          return
        }
        
        const response = await environmentAPI.validateYaml({ yaml_config: environmentForm.yaml_config })
        if (response.valid) {
          ElMessage.success(response.message)
        } else {
          ElMessage.error(response.message)
        }
      } catch (error) {
        ElMessage.error('YAML格式验证失败: ' + (error.response?.data?.message || error.message))
      }
    }

    const formatYaml = async () => {
      try {
        if (!environmentForm.yaml_config.trim()) {
          ElMessage.warning('YAML配置为空')
          return
        }
        
        const response = await environmentAPI.formatYaml({ yaml_config: environmentForm.yaml_config })
        if (response.valid) {
          environmentForm.yaml_config = response.formatted_yaml
          ElMessage.success(response.message)
        } else {
          ElMessage.error(response.message)
        }
      } catch (error) {
        ElMessage.error('YAML格式化失败: ' + (error.response?.data?.message || error.message))
      }
    }

    const copyYamlConfig = () => {
      if (selectedEnvironment.value && selectedEnvironment.value.yaml_config) {
        navigator.clipboard.writeText(selectedEnvironment.value.yaml_config)
          .then(() => {
            ElMessage.success('YAML配置已复制到剪贴板')
          })
          .catch(() => {
            ElMessage.error('复制失败')
          })
      }
    }

    const deleteEnvironment = async (environment) => {
      try {
        await ElMessageBox.confirm(`确定要删除环境"${environment.name}"吗？`, '确认删除', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        
        await environmentAPI.delete(environment.id)
        ElMessage.success('删除成功')
        loadEnvironments()
      } catch (error) {
        if (error !== 'cancel') {
          console.error('删除环境失败:', error)
        }
      }
    }

    const saveEnvironment = async () => {
      if (!environmentFormRef.value) return
      
      try {
        await environmentFormRef.value.validate()
        saving.value = true
        
        if (editingEnvironment.value) {
          await environmentAPI.update(editingEnvironment.value.id, environmentForm)
          ElMessage.success('更新成功')
        } else {
          await environmentAPI.create(environmentForm)
          ElMessage.success('创建成功')
        }
        
        showCreateDialog.value = false
        loadEnvironments()
        resetForm()
      } catch (error) {
        console.error('保存环境失败:', error)
      } finally {
        saving.value = false
      }
    }

    const resetForm = () => {
      editingEnvironment.value = null
      Object.assign(environmentForm, {
        name: '',
        base_url: '',
        description: '',
        yaml_config: '',
        is_active: true
      })
      if (environmentFormRef.value) {
        environmentFormRef.value.resetFields()
      }
    }

    const formatDate = (dateString) => {
      if (!dateString) return '-'
      return new Date(dateString).toLocaleString('zh-CN')
    }

    onMounted(() => {
      loadEnvironments()
    })

    return {
      loading,
      saving,
      showCreateDialog,
      showYamlDialog,
      editingEnvironment,
      selectedEnvironment,
      environments,
      environmentForm,
      environmentFormRef,
      formRules,
      editEnvironment,
      viewYamlConfig,
      deleteEnvironment,
      saveEnvironment,
      loadYamlTemplate,
      validateYaml,
      formatYaml,
      copyYamlConfig,
      formatDate
    }
  }
}
</script>

<style scoped>
.environments {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-header h2 {
  margin: 0;
  color: #303133;
}

.yaml-editor-container {
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  overflow: hidden;
}

.yaml-toolbar {
  background-color: #f5f7fa;
  padding: 8px 12px;
  border-bottom: 1px solid #dcdfe6;
  display: flex;
  gap: 8px;
}

.yaml-textarea {
  font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', monospace;
  font-size: 13px;
  line-height: 1.5;
}

.yaml-view-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
  padding-bottom: 12px;
  border-bottom: 1px solid #ebeef5;
}

.yaml-view-header h4 {
  margin: 0;
  color: #303133;
}
</style> 